package com.etoak.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import com.etoak.common.core.constant.CommonConstant;
import com.etoak.common.core.vo.ResultVO;
import com.etoak.common.redis.service.RedisService;
import com.etoak.vo.CodeVO;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/code")
public class CodeController {
    @Autowired
    RedisService redisService;

    @Autowired
    DefaultKaptcha defaultKaptcha;

    /**
     * get /code/getCode
     * @return
     */
    @GetMapping("/getCode")
    public ResultVO<CodeVO> getCode() throws IOException {
        //text="2+2=?@4
        String text = defaultKaptcha.createText();
        /**
         *
         */
        String[] textArray = text.split("@");

        /**
         * 验证码写到redis中
         */
        String uuid= IdUtil.simpleUUID();
        redisService.setex(CommonConstant.REDIS_CODE_KEY+uuid,textArray[1],
                5, TimeUnit.MINUTES);

        BufferedImage bufferedImage = defaultKaptcha.createImage(textArray[0]);
        ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
        ImageIO.write(bufferedImage,"png",outputStream);

        /**
         * 图片的base64编码
         */
        String base64 = Base64.encode(outputStream.toByteArray());

        CodeVO codeVO=new CodeVO(uuid,"data:image/png;base64," + base64);
        return ResultVO.success(codeVO);
    }

}
